<template>
  <div>
    <!-- 导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 内容主题区域 -->
    <el-card class="box-card">
      <el-button type="primary">添加按钮</el-button>
      <!-- 表格 -->
      <el-table :data="roleList" border>
        <el-table-column type="expand" width="180">
          <template slot-scope="scope">
              <!-- 通过scope拿到一级菜单 然后通过一级菜单的item项拿到二级菜单,以此类推 -->
            <!-- 栅格系统 -->
            <el-row v-for="(item, index) in scope.row.children" :key="item.id" :class="['bdbottom', index === 0 ? 'bdtop' : '', 'vcenter']">
              <!-- 渲染一级菜单 -->
              <el-col :span="5">
                <el-tag type="primary" closable="" @close="closeBox(scope.row,item.id)">
                  {{ item.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级, 三级菜单 -->
              <el-col :span="19">
                <!-- 通过 for 循环 嵌套渲染二级权限 -->
                <el-row :class="[i2 === 0 ? '' : 'bdtop', '', 'vcenter']" v-for="(item2, i2) in item.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable  @close="closeBox(scope.row,item2.id)" >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable @close="closeBox(scope.row,item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#" width="180"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称" width="180"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" width="180"></el-table-column>
        <el-table-column prop="address" label="操作">
            <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="editRole" >编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
                <el-button type="warning" icon="el-icon-setting" size="mini" @click="userRights(scope.row)">分配权限</el-button>
            </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog title="提示" :visible.sync="dialogVisible" width="50%" @close="cancle">
      <!-- node-key 点击节点后,获得的是被点击节点的id值 -->
      <el-tree :data="rightList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defkeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addrights()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleList: [],
      dialogVisible: false,
      rightList: [],
      rolesID: '',
      // 树形控件的数据绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      //默认选中的权限ID值 要想获得此ID 必须获得 三级 菜单中的ID值
      //利用递归函数,获取三级菜单中被选择项
      defkeys: []
    }
  },
  created() {
    this.getRoleList();
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get("roles");
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取列表失败");
      }
      this.roleList = res.data;
    },
    editRole() {
      this.dialogVisible = true;
    },
    //根据id删除对应权限
    closeBox (role, id2) {
        console.log(role, id2);
        // 弹框提示用户是否删除权限
        this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {data: res} = await this.$http.delete(`roles/${role.id}/rights/${id2}`)
          console.log(res);
          if (res.meta.status !== 200) return this.$message.error('取消权限失败')
          this.$message.success('取消权限成功')
          //为当前角色赋最新的值  类似于role.children = scope.row.children  scope.row = res.data
          role.children = res.data
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    //展示分配权限的对话框
    async userRights(role) {
        //获取所有权限
        const {data: res } = await this.$http.get('rights/tree')
        if (res.meta.status !== 200) return this.$message.error('获取权限列表失败') 
        this.$message.success('获取权限列表成功')
        console.log(res);
        this.rightList = res.data
        this.getLeafkeys(role, this.defkeys)
        this.dialogVisible = true;
        this.rolesID = role.id
    },
    getLeafkeys(node, arr) {
      //如果是三级节点,那么就向数组中添加其ID值
      if (!node.children) {
        return arr.push(node.id)
      }
      //如果不是三级节点, 那么就遍历整个node数组
      node.children.forEach(element => {
        this.getLeafkeys(element, arr)
      });
    },
    //监听分配权限的对话框关闭事件
    cancle () {
      this.defkeys = []
    },
    //给角色授权
    async addrights () {
      this.dialogVisible = false
      const keys = [
        //获取树形控件的三级菜单节点
        ...this.$refs.treeRef.getCheckedKeys(),
        //获取树形控件的半选节点
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // console.log(keys);
      const IDstr = keys.join(',')
      const {data: res } = await this.$http.post(`roles/${this.rolesID}/rights`, {rids: IDstr})
      if (res.meta.status !== 200) return this.$message.error('更新权限失败')
      this.$message.success('更新权限成功')
      this.getRoleList()
    }
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 10px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
    display: flex;
    align-items: center;
}
</style>